<template>
  <div class="options-editor">
    <div v-if="!component || !component.children">
      <p>请先选择一个选项组组件。</p>
    </div>
    <div v-else>
      <div v-for="(option, index) in component.children" :key="option.id" class="option-item">
        <el-input v-model="option.props.textContent" placeholder="显示文本" size="small" class="input-text" @input="(value: string) => handleOptionUpdate(option.id, 'textContent', value)" />
        <el-input v-model="option.props.label" placeholder="选项值" size="small" class="input-label" @input="(value: string) => handleOptionUpdate(option.id, 'label', value)" />
        <el-button type="danger" :icon="Delete" circle size="small" @click="removeOption(option.id)" />
      </div>
      <el-button type="primary" :icon="Plus" @click="addOption" style="margin-top: 10px;">添加选项</el-button>
    </div>
  </div>
</template>

<script setup lang="ts">
import { computed } from 'vue';
import { useDesignStore, type CanvasComponent } from '@/stores/designStore';
import { Delete, Plus } from '@element-plus/icons-vue';

const props = defineProps<{
  componentId: string | null;
}>();

const designStore = useDesignStore();

// 获取当前选中的 Group 组件
const component = computed(() => {
  if (!props.componentId) return null;
  // 使用 getter 获取以确保响应性
  return designStore.findComponentById(designStore.canvasComponents, props.componentId);
});

// 确定子选项的类型 (radio or checkbox)
const optionType = computed<'el-radio' | 'el-checkbox' | null>(() => {
    if (component.value?.type === 'el-radio-group') return 'el-radio';
    if (component.value?.type === 'el-checkbox-group') return 'el-checkbox';
    return null;
});

// 添加选项
const addOption = () => {
  if (props.componentId && optionType.value) {
    designStore.addOptionToGroup(props.componentId, optionType.value);
    // Note: The child list should update reactively due to store changes.
  }
};

// 移除选项
const removeOption = (optionId: string) => {
  if (props.componentId) {
    designStore.removeOptionFromGroup(props.componentId, optionId);
     // Note: The child list should update reactively due to store changes.
  }
};

// ++ 处理选项更新，调用 store action 以便记录历史 ++
const handleOptionUpdate = (optionId: string, propKey: 'label' | 'textContent', value: string) => {
  if (props.componentId) {
    designStore.updateOptionInGroup(props.componentId, optionId, { [propKey]: value });
  }
};

</script>

<style scoped>
.options-editor {
  padding: 10px;
  border-top: 1px solid #eee; /* Add a separator line */
  margin-top: 10px;
}
.option-item {
  display: flex;
  align-items: center;
  margin-bottom: 8px;
}
.input-text {
  flex-grow: 1;
  margin-right: 8px;
}
.input-label {
 width: 100px; /* Fixed width for label value input */
 margin-right: 8px;
}
</style> 